//获取应用实例
const app = getApp()

Page({
    data: {
      boxId:"",
      box:{},
      scoreItems:[],
      reports:[],
      isShowSubmit:false,
      reportId:'',
      isShowRemove:false,
      selectedId:"",
      isShowReport:false,
      isBackReport:false,
    },

    onLoad: function(options) {
      if (options != null){
        const boxId= options.boxId;
        this.setData({boxId})
        var that = this;
        wx.request({
          url: app.globalData.url+'/wechat/box?boxId='+boxId,
          method: 'get',
          success: res2 => {
            this.setData({
              box:res2.data||{},
              scoreItems:res2.data&&res2.data.scoreItems||[]});
            wx.setNavigationBarTitle({
              title: res2.data&&res2.data.name||"未查到作业箱"
          })
          wx.request({
            url: app.globalData.url+'/wechat/student_reports',
            data: {
              username: app.globalData.localuserinfo.username,
              boxId: boxId,
            },
            method: 'POST',
            header: {
              'content-type': 'application/json'
            },
            success: res2 => {
              const userReports=res2.data||[];
              const reports=that.data.reports;
              let flag = false;
              that.data.scoreItems.forEach((item,index) => {
              flag = true
              userReports.forEach(report => {
                  if (report.score_item === item) {
                    reports[index] = report
                    flag = false
                  }
              })
              if (flag) {
                  reports[index] ={
                      score_item:item,
                      status:'未上传',
                      boxId: boxId,
                      '_id': (Math.random()*10000).toString()
                  }
              }
              this.setData({reports});
          })
            }
          })
          }
        })
        
      }
    },
    iconClick:function(e){
      const score_item=e.target.id;
      const that=this;
      const box=this.data.box;
      if(box.reportType==='text'){
          // 选择文件，设置上传的类型和数量
          wx.chooseMessageFile({
            count: 1,
            type: 'file',
            success (res) {
              // tempFilePath可以作为 img 标签的 src 属性显示图片
              const tempFilePaths = res.tempFiles;
              const file=tempFilePaths[0];
              const fileName=file.name;
              if(!fileName.endsWith('pdf')){
                wx.showToast({
                  title: '请上传PDF类型文件！',
                  icon: 'none',
                  duration: 2000
                })   
              }else{
                wx.request({
                  url: app.globalData.url + '/wechat/qiniu_upload_token',
                  method: 'get',
                  success: res => {
                    const uploadTask = wx.uploadFile({
                      url:res.data.url,
                      header: { 'content-type': 'multipart/form-data' },
                      method: 'POST',
                      filePath: file.path,
                      name: 'file',
                      formData: {
                        'token': res.data.upload_token
                      },
                      success: function (res2) {
                        const data = JSON.parse(res2.data);
                        const fileUrl=res.data.qiniu_domain+data.key;
                       wx.request({
                          url: app.globalData.url+'/wechat/creat_report',
                          data: {
                            author: app.globalData.localuserinfo.username,
                            boxId:that.data.boxId,
                            score_item,
                            fileUrl,
                            reportType:that.data.box.reportType,
                            status:"草稿",
                            token:app.globalData.token
                          },
                      method: 'POST',
                       header: {
                        'content-type': 'application/json'
                       },
                      success: res2 => {
                        const report=res2.data;
                        const reports=that.data.reports;
                        const index=reports.findIndex(r=>r.score_item===score_item);
                        reports[index]=report;
                        that.setData({reports})
                    }
                  })
                      },
                      fail: function (err) {
                        console.log(err);
                        wx.showToast({
                          title: '上传失败，图片服务器出错：' + err.errMsg,
                          icon: 'none',
                          duration: 2000
                        })
                      
                      },
                    })
                    uploadTask.onProgressUpdate((res) => {
                      if (res.progress == 100) {
                        wx.showToast({
                          title: '上传成功！',
                          icon: 'success',
                          duration: 2000
                        })
                  
                      }
                    })
                  },
                  fail: function (err) {
                    console.log(err);
                    wx.showToast({
                      title: '上传失败，获取token出错：' + err,
                      icon: 'none',
                      duration: 2000
                    })

                  }
                });
              }
            }
          })
      }else if(box.reportType==='image'){
        wx.navigateTo({
          url: "../student_report_image/report?boxId="+this.data.boxId+"&score_item="+score_item,
        });
      }
      else{
          wx.navigateTo({
            url: "../student_report/report?boxId="+this.data.boxId+"&score_item="+score_item,
          });
      }
     
    },

    view_report:function(e){
      const reportId=e.target.id;
      console.log('reportId',reportId)
      const box=this.data.box;
      const reportType=box.reportType;
      console.log('reportType',reportType)
      if(reportType==='image'){
        wx.navigateTo({
          url: "../report_image_view/report_view?reportId="+reportId
        });
      }else if(reportType==='text'){
        this.setData({isShowReport:true})
      }
      else{
        wx.navigateTo({
          url: "../report_view/report_view?reportId="+reportId
        });
      }
     
    },
    closeSubmit:function(){
      this.setData({isShowSubmit:false})
    },
    showSubmit:function(e){
      const reportId=e.target.id
      this.setData({isShowSubmit:true,reportId})
    },
    submitReport:function(){
      const that=this;
      wx.request({
        url: app.globalData.url+'/wechat/update_report',
        data: {
          id: that.data.reportId,
          key:"status",
          value:'已提交/未批改',
          token:app.globalData.token
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: res2 => {
          const reports=that.data.reports;
          const index=reports.findIndex(r=>r.objectId===that.data.reportId);
          reports[index].status='已提交/未批改';
          this.setData({reports,isShowSubmit:false})
        }
      })
    },
    showRemoveReport:function(e){
      this.setData({isShowRemove:true,selectedId:e.target.id})
    },
    closeRemove:function(){
      this.setData({isShowRemove:false})
    },
    removeReport:function(){
      const that=this;
      wx.request({
        url: app.globalData.url+'/wechat/remove_report',
        data: {
          reportId: that.data.selectedId,
          token:app.globalData.token
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: res2 => {
          const reports=that.data.reports;
          const index=reports.findIndex(r=>r.objectId===that.data.selectedId);
          reports[index].status='未上传';
          this.setData({reports,isShowRemove:false})
        }
      })
    },

    backReport:function(e){
      this.setData({isBackReport:true,selectedId:e.target.id})
    },
    closeBack:function(){
      this.setData({isBackReport:false})
    },
    withdrawReport:function(){
      const that=this;
      wx.request({
        url: app.globalData.url+'/wechat/update_report',
        data: {
          key: 'status',
          value: '草稿',
          id: that.data.selectedId,
          token:app.globalData.token
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: res2 => {
          const reports=that.data.reports;
          const index=reports.findIndex(r=>r.objectId===that.data.selectedId);
          reports[index].status='草稿';
          that.setData({reports,isBackReport:false})
        }
      })
    }


  
})
